/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package FormController;

import Service.MainService;
import Service.OTPService;
import Util.StringUtils;
import Util.ValidatorUtils;
import java.io.IOException;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Peat
 */
public class MainFormController extends BaseFormController {

    public MainFormController() {
        super("MainController.properties",
                null,
                null);
    }

    // Authenticate
    protected ModelAndView Index_Console(
            ModelAndView mv, HttpServletRequest request,
            HttpServletResponse response)
            throws NamingException, JSONException, IOException
    {
        String action = request.getParameter("action");
        HttpSession session = request.getSession();
        JSONObject json = new JSONObject();
        
        if (action.equals("login")) {

            // Call login service
            MainService ms = (MainService) new MainService();
            ms.doLogin(request);

            // Formulate output.
            // should add error code and message on false.
            json.put("result", ValidatorUtils.validateSession(request));
            
            String redirectPage = (String) request.getSession().getAttribute("redirectPage");
            if (StringUtils.isNullOrEmpty(redirectPage) == false) {
                // unset
                request.getSession().removeAttribute("redirectPage");
                json.put("redirectPage", redirectPage);
            }
        } else if (action.equals("logout")) {
            session.removeAttribute("InfoSubscriber");
            session.removeAttribute("InfoAuthenBean");
            
            json.put("result", true);
            json.put("redirectPage", "index.html");
        }
        mv.addObject("result", json.toString());
        return mv;
    }

    protected ModelAndView ActivateCodeSSO_Console(
            ModelAndView mv, HttpServletRequest request,
            HttpServletResponse response)
            throws NamingException, JSONException, IOException {
        
        String action = request.getParameter("action");
        HttpSession session = request.getSession();
        OTPService otpService = new OTPService();

        if (action.equals("activeCodeOTP")) {
            otpService.activeCodeOTP(request);
        } else if (action.equals("genCodeOTP")) {
            otpService.genCodeOTP(request);
        }
        return mv;
    }
}